<template>
    <div class="jackpot-result">

        <common-table>
            <template #header>
                <div class="flex-x-start">
                    <el-input style="width: 250px;" v-model="state.queryParams.keyword"
                        placeholder="请输入游戏期号"></el-input>
                    <el-button style="margin-left: 10px;" type="primary" @click="onSearch">查询</el-button>
                    <el-button @click="handleDispose('add')" style="margin-left: 10px;" type="primary">
                        添加单期
                    </el-button>
                </div>

            </template>

            <el-table align="center" height="100%" border :data="state.gameResultList">
                <el-table-column fixed="left" align="center" min-width="200" prop="gameCode"
                    label="游戏期号"></el-table-column>
                <el-table-column align="center" min-width="100" prop="dice1" label="骰子1">
                    <template #default="{ row }">
                        <span v-if="row.dice1 === 0">-</span>
                        <img v-else :width="30" :height="30" :src="state.dicMap[row.dice1]" alt="" />
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="100" prop="dice2" label="骰子2">
                    <template #default="{ row }">
                        <span v-if="row.dice2 === 0">-</span>
                        <img v-else :width="30" :height="30" :src="state.dicMap[row.dice2]" alt="" />
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="100" prop="dice3" label="骰子3">
                    <template #default="{ row }">
                        <span v-if="row.dice3 === 0">-</span>
                        <img v-else :width="30" :height="30" :src="state.dicMap[row.dice3]" alt="" />
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="100" prop="sum" label="点数和">
                    <template #default="{ row }">
                        <span v-if="row.sum === 0">-</span>
                        <span v-else>{{ row.sum }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="100" label="大/小">
                    <template #default="{ row }">
                        <span v-if="row.sum === 0">-</span>
                        <span v-else>{{ row.sum > 10 ? '大' : '小' }}</span>
                    </template>

                </el-table-column>
                <!-- 状态 -->
                <el-table-column align="center" min-width="100" prop="status" label="开奖状态">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">{{ row.status === 1 ? '已开奖' : '未开奖'
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="220" prop="resultTime" label="开奖时间">
                    <template #default="{ row }">
                        <el-countdown v-if="row.resultTime && row.status === 0" title="开奖" @finish="() => onFinish(row)"
                            format="HH:mm:ss" :value="new Date(row.resultTime)" />
                        <span v-else>{{ formatDateTime(row.resultTime) }}</span>
                    </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column fixed="right" align="center" width="180" label="操作">
                    <template #default="{ row }">
                        <div class="flex justify-center">
                            <el-button type="primary" size="small" v-if="row.status === 0"
                                @click="handleDispose('bet', row)">投注</el-button>
                            <el-button type="primary" size="small" @click="handleDispose('detail', row)">详情</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-pagination v-model:current-page="state.queryParams.page" v-model:page-size="state.queryParams.limit"
                    @current-change="onSearch" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.total">
                </el-pagination>
            </template>
        </common-table>
        <el-dialog v-model="dialogVisible" width="400px" :title="state.dialogTitle">
            <div>
                <el-form :model="state.form" ref="formRef" label-width="auto">
                    <el-form-item label="是否随机点数">
                        <el-switch v-model="state.form.isRandom" active-text="随机" inactive-text="手动"></el-switch>
                    </el-form-item>
                    <template v-if="!state.form.isRandom">
                        <el-form-item label="骰子1">
                            <el-select v-model="state.form.dice1" placeholder="请选择">
                                <el-option v-for="item, key in state.dicMap" :key="key" :value="key">
                                    <div class="flex-x-start" style="width: 100%;">
                                        <img :src="item" alt="" style="width: 20px; height: 20px;" />
                                        <span class="ml-10"> {{ key }}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="骰子2">
                            <el-select v-model="state.form.dice2" placeholder="请选择">
                                <el-option v-for="item, key in state.dicMap" :key="key" :value="key">
                                    <div class="flex-x-start" style="width: 100%;">
                                        <img :src="item" alt="" style="width: 20px; height: 20px;" />
                                        <span class="ml-10"> {{ key }}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="骰子3">
                            <el-select v-model="state.form.dice3" placeholder="请选择">
                                <el-option v-for="item, key in state.dicMap" :key="key" :value="key">
                                    <div class="flex-x-start" style="width: 100%;">
                                        <img :src="item" alt="" style="width: 20px; height: 20px;" />
                                        <span class="ml-10"> {{ key }}</span>
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </template>

                </el-form>
            </div>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSubmit">确定</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogBetVisible" width="700px" title="详情">
            <el-descriptions title="游戏结果" direction="vertical" border>
                <el-descriptions-item :rowspan="2" :width="140" label="期号" align="center">
                    {{ state.currentRow.gameCode }}
                </el-descriptions-item>
                <el-descriptions-item :width="140" label="游戏类型" align="center">
                    三分快
                </el-descriptions-item>
                <el-descriptions-item align="center" label="开奖状态">
                    <el-tag :type="state.currentRow.status === 1 ? 'success' : 'danger'">{{ state.currentRow.status
                        === 1 ? '已开奖' : '未开奖' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item align="center" label="开奖结果">
                    <div v-if="state.currentRow.status === 1" class="flex-x-start">
                        <img class="mr-20" :src="state.dicMap[state.currentRow.dice1]" alt=""
                            style="width: 50px; height: 50px;" />
                        <img class="mr-20" :src="state.dicMap[state.currentRow.dice2]" alt=""
                            style="width: 50px; height: 50px;" />
                        <img class="mr-20" :src="state.dicMap[state.currentRow.dice3]" alt=""
                            style="width:50px; height: 50px;" />
                    </div>
                    <div v-else>---</div>
                </el-descriptions-item>
                <el-descriptions-item :width="140" label="点数和" align="center">
                    {{ state.currentRow.sum }}
                </el-descriptions-item>
            </el-descriptions>
            <el-descriptions title="投注记录" direction="vertical" border class="mt-20">
            </el-descriptions>
            <el-table :data="state.currentRow.bets" height="400" border>
                <el-table-column prop="gameUserId" show-overflow-tooltip label="游戏玩家ID" align="center" />
                <el-table-column prop="betType" label="玩法" align="center" />
                <el-table-column prop="result" label="投注方案">
                    <template #default="{ row }">
                        <div>本金：{{ row.betAmount }} 元 </div>
                        <div>倍数：{{ row.betCount }}倍</div>
                    </template>
                </el-table-column>
                <el-table-column prop="result" label="压注" align="center">
                </el-table-column>

                <el-table-column prop="betAmount" label="共投金额" align="center">
                    <template #default="{ row }">
                        {{ row.betAmount * row.betCount }}
                        元
                    </template>
                </el-table-column>
                <el-table-column width="150" label="是否中奖" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.isWin && state.currentRow.status === 1 ? 'success' : 'danger'">{{
                            state.currentRow.status === 0 ? '未开奖' : row.isWin ? '中奖金额' + row.winAmount + '元' : '未中奖'
                        }}</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>

        <el-drawer size="900px" v-model="drawerVisible" direction="ltr">
            <template #header>
                <h4>投注</h4>
            </template>

            <el-card shadow="never" class="mb-20" v-for="val, key in state.oddsMap">
                <template #header>
                    <h4>{{ key }}</h4>
                </template>
                <div v-if="String(key) !== '二同号单选' && String(key) !== '二同号复选' && String(key) !== '三连号通选'">
                    <el-checkbox-group v-model="state.betMap[key].value">
                        <el-checkbox-button class="check-button ml-10 mr-10 mb-10" v-for="it in val" :key="it.id"
                            :value="it.oddsName">
                            <div>{{ filterNumber(it.oddsName) }}</div>
                            <div class="mt-6">1:{{ it.oddsValue }}</div>
                        </el-checkbox-button>
                    </el-checkbox-group>
                </div>

                <div v-if="String(key) === '二同号单选'">
                    <div class="mb-10 red-text">
                        说明：二同号单选：两个数字相同并且单也相同
                    </div>
                    <div class="mb-10 red-text"> 赔率：1:{{ val[0].oddsValue }}</div>
                    <!-- 同号单选 -->
                    双同： <el-checkbox-group v-model="state.betMap[key].value[0]">
                        <el-checkbox-button class="check-button ml-10 mr-10 mb-10" v-for="it in 6" :key="it"
                            :value="it">
                            <div>{{ it }}</div>
                        </el-checkbox-button>
                    </el-checkbox-group>
                    单： <el-checkbox-group v-model="state.betMap[key].value[1]">
                        <el-checkbox-button class="check-button ml-10 mr-10 mb-10" v-for="it in 6" :key="it"
                            :value="it">
                            <div>{{ it }}</div>
                        </el-checkbox-button>
                    </el-checkbox-group>
                </div>
                <div v-if="String(key) === '二同号复选'" class="">
                    <div class="mb-10 red-text">
                        说明：二同号复选：两个数字相同
                    </div>
                    <div class="mb-10 red-text"> 赔率：1:{{ val[0].oddsValue }}</div>
                    <el-checkbox-group v-model="state.betMap[key].value">
                        <el-checkbox-button class="check-button ml-10 mr-10 mb-10" v-for="it in 6" :key="it"
                            :value="it">
                            <div>{{ it }}</div>
                        </el-checkbox-button>
                    </el-checkbox-group>
                </div>
                <div v-if="String(key) === '三连号通选'" class="">
                    <div class="mb-10 red-text">
                        说明：三连号通选：三个连续的数字
                    </div>
                    <div class="mb-10 red-text"> 赔率：1:{{ val[0].oddsValue }}</div>
                    <el-checkbox-group v-model="state.betMap[key].value">
                        <el-checkbox-button class="check-button ml-10 mr-10 mb-10" v-for="it in state.betThreeList"
                            :key="it" :value="it">
                            <div>{{ it }}</div>
                        </el-checkbox-button>
                    </el-checkbox-group>
                </div>
            </el-card>
            <template #footer>
                <div style="flex: auto">
                    <el-button @click="drawerVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">投注</el-button>
                </div>
            </template>
        </el-drawer>

        <el-dialog v-model="betDialogVisible" width="700px" title="投注金额及注数">
            <el-table :data="state.betForm" border>
                <el-table-column align="center" width="100" prop="betType" label="玩法"></el-table-column>
                <el-table-column align="center" width="100" prop="value" label="投注方式"></el-table-column>
                <el-table-column align="center" min-width prop="betAmount" label="单注金额">
                    <template #default="{ row }">
                        <el-input type="number" v-model="row.betAmount" :min="1" :max="1000000" />
                    </template>
                </el-table-column>
                <el-table-column align="center" min-width="200" prop="betCount" label="倍数">
                    <template #default="{ row }">
                        <el-input-number v-model="row.betCount" :min="1" :max="1000000" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <el-button @click="betDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmBet">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang='ts'>
import CommonTable from '@/components/common-table.vue'
import { JackpotApi } from '@/api/jackpot'
import { computed, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import oneSvg from '@/assets/imgs/one.svg'
import twoSvg from '@/assets/imgs/tow.svg'
import threeSvg from '@/assets/imgs/three.svg'
import fourSvg from '@/assets/imgs/four.svg'
import fiveSvg from '@/assets/imgs/five.svg'
import sixSvg from '@/assets/imgs/six.svg'
import { formatDateTime } from '@/utils/formart'
import { useJackpotStore } from '@/store'
import { storeToRefs } from 'pinia'

const store = useJackpotStore()
const { userInfo } = storeToRefs(store)


const queryInit = {
    page: 1,
    limit: 10,
    keyword: ''
}
let timer: any = null

const dialogVisible = ref<boolean>(false)
const dialogBetVisible = ref<boolean>(false)
const drawerVisible = ref<boolean>(false)
const betDialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)

const state = reactive<any>({
    queryParams: Object.assign({}, queryInit),
    gameResultList: [],
    oddsList: [],
    oddsMap: {},
    total: 0,
    currentRow: {},
    dialogType: 'add',
    dialogTitle: '新值单期（后期自动触发定时任务）',
    form: {},
    dicMap: {
        1: oneSvg,
        2: twoSvg,
        3: threeSvg,
        4: fourSvg,
        5: fiveSvg,
        6: sixSvg
    },
    betMap: {},
    betThreeList: [123, 234, 345, 456],
    betForm: []
})

const betMapCom = computed(() => {
    return Object.keys(state.betMap).map(key => {
        return state.betMap[key].value.length > 0 ? state.betMap[key] : null
    }).filter(item => item !== null).map(e => {
        return {
            ...e,
            betAmount: 1,
            betCount: 1
        }
    })
})

const onSearch = () => {
    JackpotApi.getGameResultList(state.queryParams).then(res => {
        state.gameResultList = res.data.data
        state.total = res.data.total
        if (state.currentRow.id) {
            state.currentRow = state.gameResultList.find((item: any) => item.id === state.currentRow.id) || {}
        }
    })
}

const getOddsList = () => {
    JackpotApi.getOddRuleList({
        page: 1,
        limit: 9999,
        keyword: '',
        isActive: 1
    }).then(res => {
        state.oddsList = res.data.data
        state.oddsMap = res.data.data.reduce((acc: any, cur: any) => {
            acc[cur.betType] ? acc[cur.betType].push(cur) : acc[cur.betType] = [cur]
            return acc
        }, {})
        initBetMap()
    })
}

const initBetMap = () => {
    Object.keys(state.oddsMap).forEach(key => {
        state.betMap[key] = {
            value: [],
            betType: key,
            oddsName: state.oddsMap[key][0].oddsName,
            oddsValue: state.oddsMap[key][0].oddsValue
        }
    })
    state.betForm = []
}

const handleDispose = (type: string, row?: any) => {
    state.currentRow = row || {}
    switch (type) {
        case 'add':
            dialogVisible.value = true
            state.dialogType = 'add'
            state.dialogTitle = '新值单期（后期自动触发定时任务）'
            state.form = {}
            break
        case 'detail':
            dialogBetVisible.value = true
            break
        case 'bet':
            drawerVisible.value = true
            initBetMap()
            break
    }
}

const filterNumber = (str: string) => {
    const reg = /\d+/g
    if (reg.test(str)) {
        return str.replace(/[^0-9]/g, '')
    } else {
        return str
    }
}

const onSubmit = () => {
    if (!state.form.isRandom) {
        if (!state.form.dice1 || !state.form.dice2 || !state.form.dice3) {
            ElMessage.error('请选择骰子点数')
            return
        }
    }
    state.form.isRandom = !!state.form.isRandom
    state.form.dice1 = Number(state.form.dice1) || 0
    state.form.dice2 = Number(state.form.dice2) || 0
    state.form.dice3 = Number(state.form.dice3) || 0
    JackpotApi.addGameResult(state.form).then(res => {
        if (res.code === 200) {
            ElMessage.success('新值单期成功')
            onSearch()
            dialogVisible.value = false
        }
    })
}

const onFinish = (row: any) => {
    if (row.status === 1) return
    if (timer) {
        clearTimeout(timer)
    }
    timer = setTimeout(() => {
        onSearch()
    }, 1000)
}

const disposeBet = () => {
    betMapCom.value.forEach((item: any) => {
        if (item.value && item.value.length) {
            item.value.forEach((val: any) => {
                state.betForm.push({
                    ...item,
                    betCount: Number(item.betCount),
                    betAmount: Number(item.betAmount),
                    value: filterNumber(String(val))
                })
            })
        }
    })
}
const confirmClick = () => {
    disposeBet()
    betDialogVisible.value = true
}

const confirmBet = () => {
    const totalBetAmount = state.betForm.reduce((acc: number, cur: any) => {
        return acc + cur.betAmount * cur.betCount
    }, 0)

    ElMessageBox.confirm(`本次投注金额为${totalBetAmount}元，是否继续？`, '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        state.betForm.forEach((item: any) => {
            item.betAmount = Number(item.betAmount)
            item.betCount = Number(item.betCount)

        })
        JackpotApi.bet({
            gameUserId: userInfo.value.id,
            gameResultId: state.currentRow.id,
            betParams: state.betForm,
            totalAmount: totalBetAmount
        }).then(res => {
            if (res.code === 200) {
                ElMessage.success('投注成功')
                betDialogVisible.value = false
                drawerVisible.value = false
                onSearch()
            }
        })
    }).catch(() => { })
}

const init = () => {
    onSearch()
    getOddsList()
}

init()


</script>
<style scoped lang='scss'>
.jackpot-result {
    height: 100%;

    .check-button {

        :deep(.el-checkbox-button__inner) {
            height: 70px;
            width: 70px;
            border-radius: 50%;
            border: 1px solid #dcdfe6 !important;
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: center;


        }

        &.is-checked {
            :deep(.el-checkbox-button__inner) {
                border: none !important;
            }
        }

    }
}
</style>
